<template>
  <el-container>
    <el-aside width="250px">
      <div class="search-row">
        <el-input placeholder="标签分类" v-model="searchTerm" clearable style="width: 150px;" size="small" />
        <el-button type="primary" @click="addTagClassification" size="small">添加分类</el-button>
      </div>
      <el-menu :default-active="activeClassification" class="tag-menu" @select="onClassificationSelect" size="small">
        <template v-for="classification in filteredClassifications">
          <el-menu-item :key="classification.id" :index="classification.id.toString()">
            <div class="menu-item-content">
              <span>{{ classification.name }}</span>
              <div class="menu-item-actions">
                <el-button type="text" size="mini" class="menu-action-btn"
                  @click.stop="editClassification(classification)">
                  <i class="el-icon-edit"></i>
                </el-button>
                <el-button type="text" size="mini" class="menu-action-btn delete-btn" style="margin-left: 0px;"
                  @click.stop="deleteClassification(classification)">
                  <i class="el-icon-delete"></i>
                </el-button>
              </div>
            </div>
          </el-menu-item>
          <template v-if="classification.children && classification.children.length">
            <el-menu-item v-for="child in classification.children" :key="child.id" :index="child.id.toString()"
              style="padding-left: 40px;">
              <div class="menu-item-content">
                <span>{{ child.name }}</span>
                <div class="menu-item-actions">
                  <el-button type="text" size="mini" class="menu-action-btn" @click.stop="editClassification(child)">
                    <i class="el-icon-edit"></i>
                  </el-button>
                  <el-button type="text" size="mini" class="menu-action-btn delete-btn"
                    @click.stop="deleteClassification(child)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                </div>
              </div>
            </el-menu-item>
          </template>
        </template>
      </el-menu>
    </el-aside>
    <el-main v-loading="loading">
      <div class="search-row">
        <el-input placeholder="标签名称" v-model="tagSearchTerm" clearable style="width: 150px;" size="small" />
        <el-button type="primary" @click="addTag" size="small">添加标签</el-button>
      </div>
      <div>
        <template v-if="tags && tags.length">
          <!-- 显示分类 -->
          <div v-for="group in groupTags" :key="'h-' + group.id" class="tag-section">
            <div class="tag-section-header">
              <div class="header-title">
                <span style="font-weight: bold;">{{ group.name }}</span>
                <el-button type="text" class="edit-group-btn" @click="editTag(group)">
                  <i class="el-icon-edit"></i>
                </el-button>
                <el-button type="text" class="delete-group-btn" @click="deleteTag(group)" 
                  style="margin-left: 0px;">
                  <i class="el-icon-delete"></i>
                </el-button>
              </div>
            </div>
            <div class="tag-list">
              <el-tag v-for="tag in group.children" :key="tag.id" closable :disable-transitions="false"
                @close="deleteTag(tag)" class="tag-item" type="info">
                {{ tag.name }}
                <el-button type="text" class="tag-edit-btn" @click.stop="editTag(tag)">
                  <i class="el-icon-edit"></i>
                </el-button>
              </el-tag>
              <el-button class="add-tag-btn" type="text" size="medium" @click="addTag(group)">
                <i class="el-icon-plus"></i>
                添加标签
              </el-button>
            </div>
          </div>

          <!-- 显示未分层的标签 -->
          <div v-if="nonGroupTags.length" class="tag-section">
            <div class="tag-list">
              <el-tag v-for="tag in nonGroupTags" :key="tag.id" closable :disable-transitions="false"
                @close="deleteTag(tag)" class="tag-item" type="info">
                {{ tag.name }}
                <el-button type="text" class="tag-edit-btn" @click.stop="editTag(tag)">
                  <i class="el-icon-edit"></i>
                </el-button>
              </el-tag>
              <el-button class="add-tag-btn" type="text" size="medium" @click="addTag(group)">
                <i class="el-icon-plus"></i>
                添加标签
              </el-button>
            </div>

          </div>
        </template>
        <el-empty v-else description="暂无标签"></el-empty>
      </div>
    </el-main>


    <tag-edit-dialog :visible.sync="tagDialogVisible" :tag="currentTag" :tcid="Number(activeClassification)"
      :parent-tags="availableParentTags" :show-parent-select="showParentSelect"
      @success="() => { this.loadTags(this.selectedClassification?.id) }" />

    <tag-classification-edit-dialog :visible.sync="classificationDialogVisible" :classification="currentClassification"
      @success="loadTagClassifications" />
  </el-container>

</template>

<script>
import api from '@/common/api';
import TagEditDialog from '@/views/admin/general/tag/components/TagEditDialog.vue'
import TagClassificationEditDialog from '@/views/admin/general/tag/components/TagClassificationEditDialog.vue'
import {omit} from "xe-utils";

export default {
  name: 'Tag',
  components: {
    TagEditDialog,
    TagClassificationEditDialog
  },
  mounted() {
    this.loadTagClassifications();
  },
  data() {
    return {
      searchTerm: '',
      tagSearchTerm: '',
      tagClassifications: [],
      tags: [],
      selectedClassification: null,
      activeClassification: '',
      loading: false,
      tagDialogVisible: false,
      currentTag: {},
      showParentSelect: true,
      classificationDialogVisible: false,
      currentClassification: {}
    };
  },
  computed: {
    groupTags() {
      if (!this.tags) return [];
      const groups = this.tags.filter(tag => !tag.parent_id && !tag.isLeaf);
      groups.forEach(group => {
        // Get leaf tags and filter by search term
        let children = this.getLeafTags(group.id);
        if (this.tagSearchTerm) {
          const searchTerm = this.tagSearchTerm.toLowerCase();
          children = children.filter(tag =>
            tag.name.toLowerCase().includes(searchTerm)
          );
        }
        group.children = children;
      });

      if (this.tagSearchTerm) {
        // only show groups with children
        return groups.filter(group => group.children.length > 0);
      }

      return groups;
    },

    nonGroupTags() {
      if (!this.tags) return [];
      let tags = this.tags.filter(tag => !tag.parentId && tag.isLeaf);
      if (this.tagSearchTerm) {
        const searchTerm = this.tagSearchTerm.toLowerCase();
        tags = tags.filter(tag =>
          tag.name.toLowerCase().includes(searchTerm)
        );
      }
      return tags;
    },

    filteredClassifications() {
      if (!this.searchTerm) return this.tagClassifications;
      return this.tagClassifications.filter(classification =>
        classification.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        (classification.children && classification.children.some(child =>
          child.name.toLowerCase().includes(this.searchTerm.toLowerCase())
        ))
      );
    },
    availableParentTags() {
      if (!this.tags) return [];
      return this.tags.filter(tag => !tag.isLeaf);
    }
  },
  methods: {
    loadTagClassifications(addedClassification) {
      api.admin_getTagClassification().then((res) => {
        this.tagClassifications = res.data.data;
        if (addedClassification) {
          // show new classification
          this.activeClassification = addedClassification.id.toString();
          this.onClassificationSelect(this.activeClassification);
        } else if (!this.activeClassification && this.tagClassifications.length > 0) {
          // no active classification, show first
          this.activeClassification = this.tagClassifications[0].id.toString();
          this.onClassificationSelect(this.activeClassification);
        }
      });
    },
    addTagClassification() {
      this.currentClassification = {};
      this.classificationDialogVisible = true;
    },
    addTag(group) {
      this.currentTag = {
        parentId: group?.id,
        color: '#366ef4',
        tcid: Number(this.activeClassification)
      };
      this.showParentSelect = !group;
      this.tagDialogVisible = true;
    },
    onClassificationSelect(index) {
      this.activeClassification = index;
      const id = parseInt(index);
      // Find the selected classification
      let found = null;
      for (const classification of this.tagClassifications) {
        if (classification.id === id) {
          found = classification;
          break;
        }
        if (classification.children) {
          const child = classification.children.find(c => c.id === id);
          if (child) {
            found = child;
            break;
          }
        }
      }
      this.selectedClassification = found;
      // Load tags for the selected classification
      if (found) {
        this.loadTags(found.id);
      }
    },
    loadTags(classificationId) {
      this.loading = true;
      api.admin_getTagList(classificationId).then(res => {
        this.tags = res.data.data;
      }).catch(err => {
        this.$message.error('加载标签失败：' + err.message);
      }).finally(() => {
        this.loading = false;
      });
    },
    editTag(tag) {
      this.currentTag = omit(tag, ['children']);
      this.showParentSelect = true;
      this.tagDialogVisible = true;
    },
    getLeafTags(parentId) {
      return this.tags.filter(tag => tag.parentId === parentId);
    },
    deleteTag(tag) {
      this.$confirm('确认删除该标签？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.admin_deleteTag(tag.id).then(res => {
          this.$message.success('删除成功');
          this.loadTags(this.selectedClassification.id);
        }).catch(() => {
          this.$message.error('删除失败');
        });
      });
    },
    editGroup(group) {
      // Logic to edit a group
    },
    editClassification(classification) {
      this.currentClassification = { ...classification };
      this.classificationDialogVisible = true;
    },
    deleteClassification(classification) {
      this.$confirm('确认删除该标签分类？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.admin_deleteTagClassification(classification.id).then(res => {
          this.$message.success('删除成功');
          this.loadTagClassifications();
        }).catch(() => {
          this.$message.error('删除失败');
        });
      });
    }
  },
};
</script>

<style scoped>
.el-container {}

.el-aside {
  background-color: #f5f7fa;
  border-right: 1px solid #e6e6e6;
  padding: 20px;
  height: auto;
}

.el-main {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.search-row {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 20px;
}

.tag-menu {
  border-right: none;
  margin-top: 10px;
}

.tag-menu .el-menu-item {
  height: 40px;
  line-height: 40px;
}

.tag-menu .el-menu-item.is-active {
  background-color: #ecf5ff;
}

.tag-section {
  margin-bottom: 12px;
}

.tag-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.tag-section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.tag-item {
  display: flex;
  align-items: center;
  padding-right: 8px;
}

.tag-edit-btn {
  padding: 0 4px;
  margin-left: 4px;
  color: #909399;
}

.tag-edit-btn:hover {
  color: #409EFF;
}

.add-tag-btn {
  border: 1px dashed #d9d9d9;
  height: 32px;
  padding: 0 10px;
  border-radius: 4px;
}

.add-tag-btn:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.add-tag-btn i {
  margin-right: 4px;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.edit-group-btn {
  padding: 2px 4px;
}

.edit-group-btn:hover {
  color: #409EFF;
}

.menu-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.menu-item-actions {
  display: none;
  gap: 4px;
}

.el-menu-item:hover .menu-item-actions {
  display: flex;
}

.menu-action-btn {
  padding: 2px 4px;
}

.menu-action-btn:hover {
  color: #409EFF;
}

.menu-action-btn.delete-btn:hover {
  color: #F56C6C;
}

.el-menu-item {
  padding-right: 12px !important;
}
</style>